﻿/// <summary>
/// data   :2016-04-19
/// author :fanzhengyong
/// 倒计时字
/// 1、直接拖到包含Text组件的父对象上或者从组件菜单上添加
/// 2、参数
///    m_countDownSec   需要倒计时的秒数
/// </summary>
using UnityEngine;
using System.Collections;
using System;
using UnityEngine.UI;

namespace UEngine
{
    [AddComponentMenu("Custom/UGUI/CountDownFont")]
    public class CountDownFont : MonoBehaviour
    {
        public int m_countDownSec = 0;
        public bool m_msecFlag = false;

        private int m_passSec = 0;
        private int m_leftSec = 0;
        private int m_hour = 0;
        private int m_min = 0;
        private int m_sec = 0;
        private int m_msec = 0;
        private bool m_stopFlag = false;
        private Text textCom = null;
        void Start()
        {
            textCom = gameObject.GetComponent<Text>();
        }
        void Update()
        {
            CountDowning();
            //currentTime.text = DateTime.Now.ToString("hh:mm:ss");
        }

        void CountDowning()
        {
            if (
                (m_stopFlag) ||
                (textCom == null)
            )
            {
                return;
            }

            m_leftSec = m_countDownSec - m_passSec;
            if (m_leftSec < 0)
            {
                m_stopFlag = true;
                m_hour = 0;
                m_min = 0;
                m_sec = 0;
                m_passSec = m_countDownSec;
            }
            else
            {
                m_hour = m_leftSec / 3600;
                m_min = (m_leftSec % 3600) / 60;
                m_sec = (m_leftSec % 3600) % 60;
                m_passSec = Mathf.CeilToInt(Time.fixedTime);
                m_msec = Mathf.Abs((int)((Time.fixedTime - m_passSec) * 1000));
            }

            if (m_msecFlag)
            {
                textCom.text = m_hour.ToString().PadLeft(2, '0') + ":" +
                   m_min.ToString().PadLeft(2, '0') + ":" +
                   m_sec.ToString().PadLeft(2, '0') + ":" +
                   m_msec.ToString().PadLeft(3, '0');
            }
            else
            {
                textCom.text = m_hour.ToString().PadLeft(2, '0') + ":" +
                   m_min.ToString().PadLeft(2, '0') + ":" +
                   m_sec.ToString().PadLeft(2, '0');
            }


        }
    }
}